package com.bdqn.utils;

import org.apache.commons.io.FilenameUtils;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpSession;
import java.io.File;
import java.io.IOException;
import java.util.UUID;

public class FileUtil {

    private FileUtil() {
    }

    public static String upload(MultipartFile file, String type, HttpSession session) throws RuntimeException {
        if (file == null || file.isEmpty()) {
            return null;
        }

        String filePath = session.getServletContext().getRealPath("/static");
        filePath = filePath + File.separator + type;

        if (file.getSize() > 1024 * 1024) {
            throw new RuntimeException("文件大小不能超过1MB");
        }
        String prefix = FilenameUtils.getExtension(file.getOriginalFilename());

        if (type.endsWith("apk")){
            if (!(prefix.equalsIgnoreCase("apk"))){
                throw new RuntimeException("文件类型错误!");
            }
        }else{
            if (!(prefix.equalsIgnoreCase("jpeg") || prefix.equalsIgnoreCase("jpg") || prefix.equalsIgnoreCase("png"))) {
                throw new RuntimeException("文件类型错误!");
            }
        }


        File fe = new File(filePath);
        if (!fe.exists()) fe.mkdirs();

        String fileName = UUID.randomUUID().toString().replace("-", "") + "." + prefix;

        try {
            file.transferTo(new File(filePath, fileName));
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        return File.separator + type + File.separator + fileName;

    }

    public static Boolean deleteFile(String fileName, HttpSession session) {
        String filePath = session.getServletContext().getRealPath("/static");
        filePath = filePath  + fileName;
        File file = new File(filePath);
        if (file.exists()) {
            file.delete();
            return true;
        }
        return false;
    }

}
